<template>
  <div class="Login">
    <header class="header flexCenter">
      <img src="../assets/imgs/public/logoWithTxt.png"
           alt="加马"
           class="logoTit-img mr20">
      <span class="titTxt">加马客户关系管理系统</span>
    </header>
    <article class="article">
      <el-form class="login-box"
               ref="form"
               :model="$data"
               :rules="rules"
               :show-message="false">
        <!-- <img src="../assets/imgs/public/logoLogin.png"
             alt="logo"
             class="w86 mt29 mb20"> -->
        <h3 class="titTxt mb35 mt35">请登录您的账号</h3>
        <div class="inp-box mb15">
          <img src="../assets/imgs/public/login.png"
               alt="用户名"
               class="w26 h26">
          <i class="bar ml10"></i>
          <el-form-item prop="account">
            <el-input placeholder="输入您的用户名"
                      v-model="account"
                      prop="account"
                      @keyup.enter.native="handleLogin">
            </el-input>
          </el-form-item>
        </div>
        <div class="inp-box mb15">
          <img src="../assets/imgs/public/password.png"
               alt="密码"
               class="w22 h26">
          <i class="bar ml14"></i>
          <el-form-item prop="password">
            <el-input type="password"
                      placeholder="请输入您的密码"
                      v-model="password"
                      prop="password"
                      @keyup.enter.native="handleLogin">
            </el-input>
          </el-form-item>
        </div>
        <div class="inp-box mb15">
          <img src="../assets/imgs/public/validator.png"
               alt="验证码"
               class="w22 h24">
          <i class="bar ml14"></i>
          <el-form-item prop="imgCode">
            <el-input placeholder="请输入验证码"
                      v-model="imgCode"
                      prop="imgCode"
                      @keyup.enter.native="handleLogin">
            </el-input>
          </el-form-item>
          <img ref="idCodeImg"
               :src="imgCodeSrc"
               alt="图形验证码"
               class="idCode-img"
               @click="ajaxGetImgCode">
        </div>
        <button type="button"
                class="login-btn btn-style-main mt25 mb40"
                @click="handleLogin">确认</button>

        <!-- <img src="../assets/imgs/public/logoLogin.png" alt="" class="car-img"> -->
      </el-form>
    </article>
    <footer class="flexCenter pt20 pb20 fs16">
      版权所有 加马（广州）互联网科技有限公司
    </footer>
  </div>
</template>

<script type="text/ecmascript-6">
import { addRoutesByAuth } from '../router'

export default {
  data () {
    return {
      rules: {
        account: [{ required: true, message: '用户名必填!' }],
        password: [{ required: true, message: '密码必填！' }],
        imgCode: [{ required: true, message: '图形验证码必填！' }]
      },
      account: '',
      password: '',
      imgCode: '',
      imgCodeSrc: '' // 验证码图片
    }
  },
  created () {
    this.ajaxGetImgCode()
  },
  mounted () {
    document.querySelector('#app').classList.remove('bgf7')
  },
  beforeDestroy () {
    document.querySelector('#app').classList.add('bgf7')
  },
  methods: {
    handleLogin () {
      this.$refs.form.validate((valid, errMsg) => {
        if (valid) {
          this.ajaxLogin()
        } else {
          this.$message.error(Object.entries(errMsg)[0][1][0].message)
        }
      })
    },
    ajaxLogin () {
      let postData = {
        account: this.account,
        password: this.password,
        imgCode: this.imgCode
      }
      this.$axios.post('/api/common/login/login', postData)
        .then(res => {
          if (res.data.meta.success) {
            window.localStorage.setItem('token', res.data.data)
            this.$store.commit('message/setUnRendCount')

            Promise.all([
              this.ajaxGetAuth(), // 权限
              this.ajaxGetAllSpecialParams(), // 字典
              this.ajaxGetUrl(), // 文件服务器路径
              this.ajaxGetTimePhase()// 放位配置时间段
            ]).then(() => {
              if (sessionStorage.getItem('toUrl')) {
                let toUrl = JSON.parse(sessionStorage.getItem('toUrl'))
                sessionStorage.removeItem('toUrl')
                this.$router.push(toUrl)
              } else {
                this.$router.push('/')
              }
            })
          } else {
            this.ajaxGetImgCode()
          }
        })
    },
    ajaxGetImgCode () {
      // 图片数据流转blob
      this.$axios({
        method: 'get',
        url: '/api/common/login/getCode/118/39',
        responseType: 'blob'
      }).then(res => {
        let tarImg = this.$refs.idCodeImg
        tarImg.onload = function (e) {
          window.URL.revokeObjectURL(tarImg.src) // 加载完毕后释放
        }
        tarImg.src = window.URL.createObjectURL(res.data)
      })
    },
    // 获取登陆账户的权限
    ajaxGetAuth () {
      return new Promise((resolve, reject) => {
        this.$axios.get('/api/common/login/getManagerDetail')
          .then(res => {
            let resData = res.data.data
            // 保存改账号所属分公司
            if (resData.companyId === 1) {
              window.sessionStorage.setItem('getManagerDetailCompanyId', 130)
            } else {
              window.sessionStorage.setItem('getManagerDetailCompanyId', resData.companyId)
            }
            // 列表转换成对象，降低搜索的时间复杂度
            let authObj = resData.functionList.reduce((obj, item) => {
              obj[item.functionNum] = item.type
              return obj
            }, {})
            let anthMenuCode = resData.menuCodeList || []
            this.$store.commit('user/initInfo', resData)
            this.$store.commit('auth/initAuthObj', authObj) // 存入vuex
            this.$store.commit('auth/initAnthMenuCode', anthMenuCode)
            addRoutesByAuth()
            resolve()
          })
      })
    },
    ajaxGetAllSpecialParams () {
      return this.$store.dispatch('specialParams/getAllParam', { vue: this })
    },
    ajaxGetTimePhase () {
      return new Promise((resolve, reject) => {
        this.$axios.get('/api/coachtesting/timePhase/get')
          .then(res => {
            let resData = res.data.data
            this.$store.commit('user/initTimePhase', resData)
            resolve()
          })
      })
    },
    ajaxGetUrl () {
      return new Promise((resolve, reject) => {
        this.$axios.get('/api/upload/getFileServerUrl')
          .then(res => {
            let resData = res.data.data
            this.$store.commit('user/initServerUrl', resData)
            resolve()
          })
      })
    }
  }
}
</script>

<style scoped rel="stylesheet/scss" type="text/scss" lang="scss">
.Login {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
}

@media screen and (max-height: 860px) {
  .header {
    display: none;
  }
}

.header {
  height: 140px;
  .logoTit-img {
    width: 200px;
    height: 71.5px;
  }
  .titTxt {
    font-size: 32px;
  }
}

.article {
  position: relative;
  flex: 1 0 655px;
  background: url("../assets/imgs/public/bg-login.png") no-repeat;
  background-size: cover;
}

.login-box {
  position: absolute;
  top: 120px;
  left: 0;
  right: 0;
  margin: auto;
  width: 449px;
  border-radius: 10px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  .titTxt {
    font-size: 26px;
  }
  /deep/ .el-form-item {
    flex: 1 1px;
    margin: 0;
  }
}

.inp-box {
  width: 330px;
  height: 50px;
  padding: 0 10px;
  border: solid 1px #ddd;
  border-radius: 5px;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  .bar {
    display: inline-block;
    height: 14px;
    width: 2px;
    background-color: #999;
  }
}

.el-input {
  /deep/ .el-input__inner {
    border: none;
    background-color: #fafafa;
  }
}

.idCode-img {
  width: 118px;
  height: 39px;
  background-color: #feb669;
}

.login-btn {
  width: 330px;
  height: 57px;
  border: none;
  line-height: 57px;
  text-align: center;
  line-height: 57px;
  font-size: 20px;
  color: #fff;
}

.car-img {
  position: absolute;
  bottom: 0;
  right: 0;
  transform: translate(50%, 84px);
  width: 223px;
  height: 197px;
}
</style>
